package com.xh.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

/**
 * @author wen
 * @apiNote
 * @since 2021-07-08
 */
@Slf4j
public class FileUtil {

    public static void createFolder(String url) {
        File file = new File(url);
        if (!file.exists()) {
            boolean mkdirs = file.mkdirs();
        }
    }

    public static String create(String url, MultipartFile file) {
        if (file.isEmpty()) return null;
        createFolder(url);
        String fileName;
        try {
            int idx = file.getOriginalFilename().indexOf(".");
            fileName = getFileName(file, idx);
            String filePath = url + "/" + fileName;
            File path = new File(filePath);
            file.transferTo(path);
        } catch (Exception e) {
            log.error("【文件上传失败】", e);
            return null;
        }
        return "accessory/" + fileName;
    }

    private static String getFileName(MultipartFile file, int idx) {
        return UUID.randomUUID().toString() + file.getOriginalFilename().substring(idx);
    }

    /**
     * 通过网络url读取图片
     *
     * @param path 图片地址
     * @return {@link InputStream}
     */
    public static InputStream getFileInputStream(String path) {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(path).openConnection();
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                return connection.getInputStream();
            }
        } catch (IOException e) {
            log.error("获取网络图片出现异常，异常为:" + e.getMessage());
        }
        return null;
    }

    /**
     * 将BufferedImage转换为InputStream
     * @param image
     * @return
     */
    public static InputStream bufferedImageToInputStream(BufferedImage image, String ext){
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "png", os);
            return new ByteArrayInputStream(os.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
